package com.king.modules.system.service.impl;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.king.common.constant.UserConstants;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.DictUtils;
import com.king.common.utils.text.StringUtils;
import com.king.framework.base.service.impl.YyBaseServiceImpl;
import com.king.modules.system.domain.SysDictDataEntity;
import com.king.modules.system.domain.SysDictTypeEntity;
import com.king.modules.system.mapper.SysDictTypeMapper;
import com.king.modules.system.service.SysDictDataService;
import com.king.modules.system.service.SysDictTypeService;

/**
 * 字典 业务层处理
 * 
 * @author king
 */
@Service
public class SysDictTypeServiceImpl extends YyBaseServiceImpl<SysDictTypeMapper, SysDictTypeEntity, Long> implements SysDictTypeService {
	@Autowired
	private SysDictTypeMapper dictTypeMapper;

	@Autowired
	private SysDictDataService dictDataService;

	/**
	 * 项目启动时，初始化字典到缓存
	 */
	@PostConstruct
	public void init() {
		try {
			loadingDictCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	@Override
	public void beforeAdd(SysDictTypeEntity entity) throws Exception {
		AssertHelper.getInstance().checkException(UserConstants.NOT_UNIQUE.equals(checkDictTypeUnique(entity)),
				"新增字典'" + entity.getDictName() + "'失败，字典类型已存在");
		super.beforeAdd(entity);
	}



	@Override
	public void beforeUpdate(SysDictTypeEntity oldEntity, SysDictTypeEntity entity) throws Exception {
		AssertHelper.getInstance().checkException(UserConstants.NOT_UNIQUE.equals(checkDictTypeUnique(entity)),
				"新增字典'" + entity.getDictName() + "'失败，字典类型已存在");
		super.beforeUpdate(oldEntity, entity);
	}



	@Override
	public void doDelete(Long uuid) throws Exception {
		Long[] uuids = {uuid};
		deleteDictTypeByIds(uuids);
	}



	@Override
	public void doDelete(Long[] uuids) throws Exception {
		deleteDictTypeByIds(uuids);
	}



	/**
	 * 根据条件分页查询字典类型
	 * 
	 * @param dictType
	 *            字典类型信息
	 * @return 字典类型集合信息
	 */
	@Override
	public List<SysDictTypeEntity> selectDictTypeList(SysDictTypeEntity dictType) {
		return dictTypeMapper.selectDictTypeList(dictType);
	}

	/**
	 * 根据所有字典类型
	 * 
	 * @return 字典类型集合信息
	 */
	@Override
	public List<SysDictTypeEntity> selectDictTypeAll() {
		return dictTypeMapper.selectDictTypeAll();
	}


	/**
	 * 根据字典类型ID查询信息
	 * 
	 * @param dictId
	 *            字典类型ID
	 * @return 字典类型
	 */
	@Override
	public SysDictTypeEntity selectDictTypeById(Long dictId) {
		return dictTypeMapper.selectDictTypeById(dictId);
	}

	/**
	 * 根据字典类型查询信息
	 * 
	 * @param dictType
	 *            字典类型
	 * @return 字典类型
	 */
	@Override
	public SysDictTypeEntity selectDictTypeByType(String dictType) {
		return dictTypeMapper.selectDictTypeByType(dictType);
	}


	/**
	 * 查询字典类型和字典数据对应的map
	 */
	@Override
	public Map<String, List<SysDictDataEntity>> selectDictMap() {
		SysDictDataEntity dictData = new SysDictDataEntity();
		dictData.setStatus("0");
		Map<Long, List<SysDictDataEntity>> dictDataMap = dictDataService.selectDictDataList(dictData).stream()
				.collect(Collectors.groupingBy(SysDictDataEntity::getMainid));
		List<SysDictTypeEntity> dictTypeList = selectDictTypeAll();
		Map<Long, SysDictTypeEntity> dictTypeMap = dictTypeList.stream().collect(Collectors.toMap(obj -> obj.getId(), Function.identity()));
		
		Map<String, List<SysDictDataEntity>> dictMap = new HashMap<String, List<SysDictDataEntity>>();
		for (Map.Entry<Long, List<SysDictDataEntity>> entry : dictDataMap.entrySet()) {
			dictMap.put(dictTypeMap.get(entry.getKey()).getDictType(), entry.getValue().stream()
					.sorted(Comparator.comparing(SysDictDataEntity::getDictSort)).collect(Collectors.toList()));
		}
		return dictMap;
	}

	
	/**
	 * 批量删除字典类型信息
	 * 
	 * @param dictIds
	 *            需要删除的字典ID
	 */
	@Override
	public void deleteDictTypeByIds(Long[] dictIds) {
		for (Long dictId : dictIds) {
			SysDictTypeEntity dictType = selectDictTypeById(dictId);
			if (dictDataService.countDictDataByMainid(dictType.getId()) > 0) {
				AssertHelper.getInstance().throwException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
			}
			dictTypeMapper.deleteDictTypeById(dictId);
			DictUtils.removeDictCache(dictType.getDictType());
		}
	}



	/**
	 * 校验字典类型称是否唯一
	 * 
	 * @param dict
	 *            字典类型
	 * @return 结果
	 */
	@Override
	public String checkDictTypeUnique(SysDictTypeEntity dict) {
		Long dictId = StringUtils.isNull(dict.getId()) ? -1L : dict.getId();
		SysDictTypeEntity dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
		if (StringUtils.isNotNull(dictType) && dictType.getId().longValue() != dictId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}
	
	
	/**
	 * 加载字典缓存数据
	 * @throws Exception 
	 */
	@Override
	public void loadingDictCache() throws Exception {
		Map<String, List<SysDictDataEntity>> dictMap = selectDictMap();
		for (Entry<String, List<SysDictDataEntity>> entry : dictMap.entrySet()) {
			DictUtils.setDictCache(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * 清空字典缓存数据
	 */
	@Override
	public void clearDictCache() {
		DictUtils.clearDictCache();
	}

	/**
	 * 重置字典缓存数据
	 * @throws Exception 
	 */
	@Override
	public void resetDictCache() throws Exception {
		clearDictCache();
		loadingDictCache();
	}


}
